import axios from "axios";
import { useCounterStore } from '@/stores/counter'
import { ElMessage } from "element-plus";

const read = axios.create({
    baseURL: "http://115.190.179.32:8000/",
    timeout: 5000,
})
//拦截器-读-请求
read.interceptors.request.use(
    config => {
        const counts = useCounterStore();
        config.headers.Authorization = "Bearer " + counts.Logins.token;
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
//拦截器-读-响应
read.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期，请重新登录");
            setTimeout(() => {
                location.href = '/'
            }, 1000)
        }

        return Promise.reject(error)
    }
)

export { read }

// 写实例（POST/PUT/DELETE 等写接口统一走网关）
const write = axios.create({
    baseURL: "http://115.190.179.32:8000/",
    timeout: 5000,
})

// 拦截器-写-请求
write.interceptors.request.use(
    config => {
        const counts = useCounterStore();
        config.headers.Authorization = "Bearer " + counts.Logins.token;
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 拦截器-写-响应
write.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期，请重新登录");
            setTimeout(() => {
                location.href = '/'
            }, 1000)
        }
        return Promise.reject(error)
    }
)

export { write }